package com.example.ch02_student.adminsDo;

import androidx.annotation.VisibleForTesting;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.example.ch02_student.R;
import com.example.ch02_student.entity.Student;
import com.example.ch02_student.utils.ResultVo;
import com.example.ch02_student.utils.RoleInfo;
import com.example.ch02_student.utils.UrlBase;
import com.google.gson.Gson;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lombok.val;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

//学生基本信息管理
public class StudentSelfInfo extends AppCompatActivity {
    private OkHttpClient okHttpClient;
    private List<Map<String,String>> list;//listView数据源
    private ListView lv;
    private EditText searchTest;
    private AlertDialog dialog;
    private String[] snos;//多选学号数据
    private boolean[] booleans ;
    private String xzsnos;//选择的学号 拼接串 151101,151102
    private SimpleDateFormat simple=new SimpleDateFormat("yyyy-MM-dd HH:mm");
    private Student[] students=null;
   // private TextView sname;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_student_self_info);

        okHttpClient=new OkHttpClient();
        lv=findViewById(R.id.stuselfLv);
        searchTest=findViewById(R.id.searchText);
        // View view= LayoutInflater.from(StudentSelfInfo.this).inflate(R.layout.activity_student_self_info_items,null);
        //sname= view.findViewById(R.id.sname);
       // sname=findViewById(R.id.sname);

        init();
        //单击lv 进入修改
        if (RoleInfo.INT_ROLE==1||RoleInfo.PERSSIONS.contains("uStuInfo")){
            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    Map<String, String> map = list.get(i);
                    Bundle bundle = new Bundle();
                    Student student =
                            new Student(map.get("sno"),map.get("sname"),map.get("img"),map.get("sex"),map.get("cclass"),map.get("major"),map.get("tel"),map.get("college"),Integer.parseInt( (map.get("age")).equals("null")?"0":(String) map.get("age")),null);
                   bundle.putSerializable("student",student);

                    //跳转
                    startActivity(new Intent(StudentSelfInfo.this,StudentSelfUpdateInfo.class).putExtras(bundle));
                }
            });
        }else {
            Toast.makeText(StudentSelfInfo.this,"无此权限",Toast.LENGTH_SHORT).show();
        }

    }

    //页面初始化
    public void init(){
        Request build = new Request.Builder().url(UrlBase.URL_BASE+"/studentSelf/selectStudentSelfAll").build();
        Call call = okHttpClient.newCall(build);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
            }
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String string = response.body().string();
                xuanran(string);

            }
        });
    }
    //搜索按钮
    public void search(View view){
        String key=searchTest.getText()+"";
        Request build = new Request.Builder().url(UrlBase.URL_BASE+"/studentSelf/selectStudentKey?s="+key).build();
        Call call = okHttpClient.newCall(build);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
            }
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                final String stringx = response.body().string();
                 students = new Gson().fromJson(stringx, Student[].class);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        lv.setAdapter(new MyAdapter());
                       // xuanran(string);
                    }
                });
               // xuanran(string);

            }
        });
    }
    //批量删除按钮
    public void multiDelete(View view){
        if (RoleInfo.INT_ROLE==1||RoleInfo.PERSSIONS.contains("dStuInfo")){
            AlertDialog.Builder builder = new AlertDialog.Builder(StudentSelfInfo.this)
                    .setMultiChoiceItems(snos, booleans, new DialogInterface.OnMultiChoiceClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i, boolean b) {
                            //将选择中的boole改为true
                            booleans[i]=b;
                        }
                    })
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            //循环拼接 已选择的字符串
                            StringBuilder string = new StringBuilder();

                            for (int j = 0; j <booleans.length ; j++) {
                                if (booleans[j]){
                                    string=string.append(","+snos[j]);
                                }
                                if (string.indexOf(",")==0){
                                    string=new StringBuilder(string.substring(1));
                                }
                            }
                            multiStu(string.toString());

                            Toast.makeText(StudentSelfInfo.this,string+"",Toast.LENGTH_SHORT).show();
                            //重新初始化
                            init();
                            dialog.dismiss();
                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialog.dismiss();
                        }
                    });
            dialog = builder.create();
            dialog.show();
        }else {
            Toast.makeText(StudentSelfInfo.this,"无此权限",Toast.LENGTH_SHORT).show();
        }



    }
    //批量删除方法
    public void multiStu(String snos){
        String a=snos;
        final int[] i=new int[1];
        Request build = new Request.Builder().url(UrlBase.URL_BASE+"/studentSelf/deleteMultiStu?snos="+a).build();
        Call call = okHttpClient.newCall(build);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
            }
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String string = response.body().string();
                ResultVo resultVo = new Gson().fromJson(string, ResultVo.class);
                if (resultVo.getCode()==1000){
                    i[0]=1;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            init();
                        }
                    });
                }

            }
        });


    }

    //数据渲染
    public void xuanran(final String json){
       // View view= LayoutInflater.from(StudentSelfInfo.this).inflate(R.layout.activity_student_self_info_items,null);
                Student[] students = new Gson().fromJson(json, Student[].class);
                snos=new String[students.length];
                booleans=new boolean[students.length];

                list=new ArrayList<>();
                Map<String,String> map;
                final String[] s =new String[] {"img","sno","sname","sex","cclass","major","tel",
                        "college","age","createTime"};
                final int[] ints=new int[]{R.id.img,R.id.sno,R.id.sname,R.id.sex,R.id.cclass,R.id.major
                        ,R.id.tel,R.id.college,R.id.age,R.id.createTime};

                for (int i = 0; i < students.length; i++) {
                    //赋值给批量删除数据源
                    snos[i]=students[i].getSno();
                    booleans[i]=false;

                    map=new HashMap<>();
                    map.put("img",students[i].getImg());
                    map.put("sno",students[i].getSno());
                    map.put("sname",students[i].getSname());

                    map.put("sex",students[i].getSex());
                    map.put("cclass",students[i].getCclass());
                    map.put("major",students[i].getMajor());
                    map.put("tel",students[i].getTel());
                    map.put("college",students[i].getCollege());
                    map.put("age",students[i].getAge()+"");
                    if (students[i].getCreateTime()!=null){
                        map.put("createTime",simple.format(students[i].getCreateTime()));

                    }

                    list.add(map);
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        SimpleAdapter simpleAdapter = new SimpleAdapter(StudentSelfInfo.this, list, R.layout.activity_student_self_info_items, s, ints);
                        lv.setAdapter(simpleAdapter);
                    }
                });

    }

    //返回
    public void back(View view){
        startActivity(new Intent(StudentSelfInfo.this,AdminsDo.class));
    }


    class MyAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return students.length;
        }

        @Override
        public Object getItem(int i) {
            return students[i];
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            View inflate = View.inflate(StudentSelfInfo.this, R.layout.activity_student_self_info_items, null);
            ImageView img=inflate.findViewById(R.id.img);
            TextView sno = inflate.findViewById(R.id.sno);
            TextView sname = inflate.findViewById(R.id.sname);
            TextView sex = inflate.findViewById(R.id.sex);
            TextView cclass = inflate.findViewById(R.id.cclass);
            TextView major = inflate.findViewById(R.id.major);
            TextView tel = inflate.findViewById(R.id.tel);
            TextView college = inflate.findViewById(R.id.college);
            TextView age = inflate.findViewById(R.id.age);

            TextView createTime = inflate.findViewById(R.id.createTime);

            img.setImageResource(Integer.parseInt(students[i].getImg()));

                sno.setText(students[i].getSno());

            //sname
            String s = students[i].getSname().replaceAll("\\[", "");
            String s1 = s.replaceAll("]", "");
            System.err.println("s1="+s1);
            sname.setText(Html.fromHtml(s1));

            sex.setText(students[i].getSex());

            //cclass
            String c = students[i].getCclass().replaceAll("\\[", "");
            String c1 = c.replaceAll("]", "");
            cclass.setText(Html.fromHtml(c1));

            //major
            String m = students[i].getMajor().replaceAll("\\[", "");
            String m1 = m.replaceAll("]", "");
            major.setText(Html.fromHtml(m1));

            tel.setText(students[i].getTel());

            //college
            String co = students[i].getCollege().replaceAll("\\[", "");
            String co1 = co.replaceAll("]", "");
            college.setText(Html.fromHtml(co1));

            age.setText(students[i].getAge()+"");
            createTime.setText(simple.format(students[i].getCreateTime()));

            return inflate;
        }
    }


}
